package com.hu.contoller;

import com.alibaba.druid.util.StringUtils;
import com.hu.context.BaseContext;
import com.hu.entity.dto.UserRegisterDTO;
import com.hu.entity.pojo.UserEntity;
import com.hu.entity.vo.Result;
import com.hu.service.UserService;
import com.hu.util.MessageUtil;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 用户有关的控制器
 * @author HYH
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private MessageUtil messageUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户发送注册验证码
     */
    @GetMapping("/sendCode")
    public Result sendCode(@RequestParam("phone") String phone, String type) throws Exception {
        String key = type + ":" + phone;
        String codeInRedis = stringRedisTemplate.opsForValue().get(key);

        if (codeInRedis != null) {
            return Result.fail("请勿频繁发送验证码");
        }

        String code = messageUtil.sendMessage(phone);
        log.info("验证码发送成功,code:{}", code);

        stringRedisTemplate.opsForValue().set(key, code, 60, TimeUnit.SECONDS);
        return Result.success("发送成功");
    }
    /**
     * 用户注册
     * @param userRegisterDTO
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("用户注册:{}", userRegisterDTO);
        // 验证该手机号是否已注册
        UserEntity userEntity = userService.selectByPhone(userRegisterDTO);
        if (userEntity != null){
            return Result.fail("该手机号已注册");
        }
        String phone = userRegisterDTO.getPhone();
        String inputCode = userRegisterDTO.getCode();

        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(inputCode)) {
            throw new RuntimeException("手机号或验证码不能为空");
        }

        String cacheCode =  stringRedisTemplate.opsForValue().get("register:" + phone);
        if (!inputCode.equals(cacheCode)) {
            throw new RuntimeException("验证码错误或已过期");
        }

        // 删除验证码，防止复用
        stringRedisTemplate.delete("register:" + phone);

        userService.register(userRegisterDTO);
        return Result.success("注册成功");
    }

    /**
     * 用户登录功能
     */
    // TODO 登录校验最后来做
    @PostMapping("/login")
    public Result login(@RequestBody UserRegisterDTO userRegisterDTO, HttpSession session) {
        log.info("用户登录:{}", userRegisterDTO);

        UserEntity user = userService.login(userRegisterDTO);

        if(user == null){
            return Result.fail("手机号或密码错误");
        }
        // 获取当前用户id
        session.setAttribute("userId", user.getId());
        Long userId = (Long) session.getAttribute("userId");
        log.info("当前登录用户的id为:{}",userId);
        return Result.success(user);

    }

    /**
     * 修改用户信息
     * @return
     */
    @PostMapping("/updateUserInfo")
    public Result<String> updateUserInfo(@RequestBody UserEntity userEntity){
        userService.updateById(userEntity);
        return Result.success("修改成功");
    }

}
